package com.wulwu.caffeine.utils;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;

import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

/**
 * 手动策略缓存工具类
 */
public class CacheUtil {

    public static Cache<String, Object> cacheManager = Caffeine.newBuilder()
            .expireAfterWrite(3, TimeUnit.HOURS)    //最后一次写入时间后 xx 小时过期
            .maximumSize(1000)  //最大数量
            .build();

    //存储
    public static void setValue(String key, Object value){
        if (StringUtils.isNotBlank(key)) {
            cacheManager.put(key,value);
        }
    }

    //指定获取
    public static Object getValue(String key){
        if (StringUtils.isNotBlank(key)) {
            return cacheManager.getIfPresent(key);
        }
        return null;
    }

    //所有缓存
    public static ConcurrentMap<String, Object> getAllCache(){
        ConcurrentMap<@NonNull String, @NonNull Object> concurrentMap = cacheManager.asMap();
        return concurrentMap;
    }

    //指定删除
    public static void delValue(String key){
        if (StringUtils.isNotBlank(key)) {
            cacheManager.invalidate(key);
        }
    }

    //批量删除
    public static void delBatchValue(List<String> keys){
        if (CollectionUtils.isNotEmpty(keys)) {
            cacheManager.invalidateAll(keys);
        }
    }

    //删除全部
    public static void delAllValue(){
       cacheManager.invalidateAll();
    }

}
